﻿var ajax = {

    // creates the xml http request object
    // which will be used to make an asynchronous call to server.
    // the try catch blocks in the following function are used for cross-browser compatibility  
    CreateXMLHttpRequest: function () {
        var xmlHTTP = null; try { xmlHTTP = new XMLHttpRequest(); }
        catch (e) {
            try { xmlHTTP = new XMLHttpRequest("Microsoft.XMLHTTP"); }
            catch (e) {
                try { xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP"); }
                catch (e) {
                    try { xmlHTTP = new ActiveXObject("Msxml2.XMLHTTP"); }
                    catch (e) { alert("Your Browser does not support Ajax"); return false; }
                }
            }
        } return xmlHTTP;
    },

    // gets the data from specified url and
    // returns the data in the callback function
    get: function (url, callback) {
        try {

            // create the new xml http object
            var httpRequest = ajax.CreateXMLHttpRequest();

            // if xmlHttpRequest object created successfuly, then go on
            if (httpRequest) {

                // set the request method to GET (for retrieving data from server) or POST (for sending data to server)
                // set the Url to get data from or to post data to
                // set async flag to true for making an async request
                httpRequest.open("GET", url, true);

                // register the 'ready state change' event
                // this will be called every time when the state
                // of httpRequest changes.
                httpRequest.onreadystatechange = function () {

                    // if httpRequest state is 4 
                    // it means response has been recieved.
                    if (httpRequest.readyState == 4) {

                        // check to see if callback is a function
                        if (typeof (callback) == 'function') {

                            // invoke the callback
                            // and pass 'responseText' to callback
                            // if you are making request to xml file then you can also use 'responseXml' to get data in xml format
                            callback(httpRequest.responseText);
                        }
                    }
                }

                // the send method is used to invoke the request
                // pass null for GET request.
                httpRequest.send(null);
            }
        } catch (e) { alert(e.message); }
    }
};